//
//  BulidingCardController.m
//  QRMaster
//
//  Created by myApple on 16/5/10.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "BulidingCardController.h"
#import "CardPowerModel.h"
#import "BulidingCardCell.h"
#import "RequestNetWork.h"

@interface BulidingCardController()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    UIImageView * submitImageView;
    UILabel * submitLabel;
    UITableView * bulidingCardTableView;
    NSMutableArray * bulidingCardArray;
    UIButton *  backBtn;
}

@end

@interface BulidingCardController ()

@end

@implementation BulidingCardController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"buildCard", @"楼栋卡");
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    [self prepareNavBtn];
    [self prepareTableView];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = NO;
    backBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    submitImageView.hidden = YES;
    backBtn.hidden = YES;
}

-(void)setBulidingArray:(NSMutableArray *)bulidingArray
{
    _bulidingArray = bulidingArray;
    bulidingCardArray = [[NSMutableArray alloc]init];
    for (CardPowerModel * model in bulidingArray) {
        [bulidingCardArray addObject:[model copy]];
    }
    [bulidingCardTableView reloadData];
}

-(void)prepareNavBtn
{
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(submit)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit",@"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
    
    float x = 0;
    float y = 0;
    float width = 56;
    float height = 40;
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [backBtn addTarget:self action:@selector(guestInfoBack) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:backBtn];
}

-(void)prepareTableView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT - 64;
    bulidingCardTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    bulidingCardTableView.delegate = self;
    bulidingCardTableView.dataSource = self;
    bulidingCardTableView.tableFooterView = [UIView new];
    bulidingCardTableView.backgroundColor = UIColorFromRGB(0xebebeb);
    [self.view addSubview:bulidingCardTableView];
    
    x = 0;
    y = 0;
    height = 39.0;
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    headerView.backgroundColor = UIColorFromRGB(0xebebeb);
    bulidingCardTableView.tableHeaderView = headerView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return bulidingCardArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * identityCell = @"cellId";
    BulidingCardCell * cell = [tableView dequeueReusableCellWithIdentifier:identityCell];
    if (!cell) {
        cell = [[BulidingCardCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identityCell];
    }
    
    CardPowerModel * model = bulidingCardArray[indexPath.row];
    cell.bulidingId = model.bulidingOrFloorId;
    cell.bulidingName = model.bulidingOrFloorName;
    cell.isSelected = model.enable;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CardPowerModel * model = bulidingCardArray[indexPath.row];
    model.enable = !model.enable;
    [bulidingCardArray replaceObjectAtIndex:indexPath.row withObject:model];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self submitStauts];
    [bulidingCardTableView reloadData];
}


#pragma mark -----------提交楼栋
-(void)submit
{
    if ([self IsHaveNetwork]) {
        return;
    }
    NSString * bulidingIdString = [self selectBuildigId];
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:_userId forKey:@"userId"];
    [postDict setValue:bulidingIdString forKey:@"buildingId"];
    __weak BulidingCardController * weakSelf = self;
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(SAVEBUILDINGCARD) params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         if (downLoadData) {
             [PromptInfoView showMessage:NSLocalizedString(@"modifyPowerSuccess", nil) superView:self.view];
             if (weakSelf.block) {
                 weakSelf.block(bulidingIdString);
             }
             [self.navigationController popViewControllerAnimated:YES];
         }
         else
         {
             [PromptInfoView showMessage:[error objectForKey:@"info"]];
             
         }
     }];
}

#pragma mark -----------判断当前的选择项和原来是否有改变
-(BOOL)judgeSelect
{
    for (NSInteger i = 0; i < bulidingCardArray.count; i++) {
        CardPowerModel * originModel = _bulidingArray[i];
        CardPowerModel * nowModel = bulidingCardArray[i];
        if (originModel.enable != nowModel.enable) {
            return YES;
        }
    }
    return NO;
}

-(void)submitStauts
{
    if ([self judgeSelect]) {
        submitImageView.userInteractionEnabled = YES;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 1.0);
    }
    else
    {
        submitImageView.userInteractionEnabled = NO;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    }
}

#pragma mark -----------提交时计算当前的选中楼栋ID
-(NSMutableString *)selectBuildigId
{
    NSMutableString * selectIdString = [[NSMutableString alloc]init];
    for (CardPowerModel * model in bulidingCardArray) {
        if (model.enable) {
            [selectIdString appendString:[NSString stringWithFormat:@"%@,",model.bulidingOrFloorId]];
        }
    }
    if (selectIdString.length > 0) {
      selectIdString = [NSMutableString stringWithString:[selectIdString substringToIndex:(selectIdString.length - 1)]] ;
    }
    return selectIdString;
}

#pragma mark ----------用户自定义返回键
-(void)guestInfoBack
{
    if ([self judgeSelect]) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"shouldSave", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"notSave", nil) otherButtonTitles:NSLocalizedString(@"save", nil), nil];
        [alterView show];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
   
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self submit];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
